package com.example.summary.thread;

import java.util.List;
import java.util.Vector;
import java.util.concurrent.Semaphore;
import java.util.function.Function;

/**
 * Created by wzn on 2019/6/25.
 */
public class ObjPool<T, R> {
    final List<T> pool;
    final Semaphore semaphore;

    public ObjPool(int size, T t) {
        pool = new Vector<T>();
        for (int i = 0; i < size; i++) {
            pool.add(t);
        }
        semaphore = new Semaphore(2);
    }

    R exec(Function<T, R> function) {
        T t = null;
        try {
            semaphore.acquire();
            t = pool.remove(0);
            return function.apply(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            pool.add(t);
            semaphore.release();
        }
        return null;
    }

    public static void main(String[] args) {
        ObjPool<Long, String> pool = new ObjPool<>(10, 2L);
        pool.exec(aLong -> {
            System.out.println(aLong);
            return aLong.toString();
        });
    }
}
